'use strict';
const uniID = require('uni-id-common');
exports.main = async (event, context) => {
  const db = uniCloud.database();
  const uniIDIns = uniID.createInstance({ context });
  
  // 兼容URL访问和直接调用
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return {
        code: 400,
        message: '参数解析错误'
      };
    }
  }

  const { action, sToken, cToken } = body;

  // 参数校验
  if (!action || !sToken || !cToken) {
    return {
      code: 400,
      message: '缺少必要参数'
    };
  }

  try {
    // 验证督导token并获取用户ID
    const sid = await uniIDIns.checkToken(sToken);
    if (sid.code !== 0) {
      return {
        code: 403,
        message: '督导身份验证失败'
      };
    }

    // 验证咨询师token并获取用户ID
    const cid = await uniIDIns.checkToken(cToken);
    if (cid.code !== 0) {
      return {
        code: 403,
        message: '咨询师身份验证失败'
      };
    }

    // 检查是否尝试建立自己与自己的关系
    if (sid.uid === cid.uid) {
      return {
        code: 400,
        message: '不能与自己建立关系'
      };
    }

    const relationCollection = db.collection('sc_relations');
    
    if (action === 's') {
      // 设置关系逻辑
      
      // 检查是否已存在相同关系
      const existingRelation = await relationCollection.where({
        supervisor_id: sid.uid,
		consultant_id: cid.uid
      }).get();

      if (existingRelation.data.length > 0) {
        return {
          code: 409,
          message: '关系已存在'
        };
      }

      // 检查咨询师是否已经有督导
      const existingSupervisor = await relationCollection.where({
        
		consultant_id: cid
      }).get();

      if (existingSupervisor.data.length > 0) {
        return {
          code: 409,
          message: '该咨询师已有督导'
        };
      }

      // 添加新关系
      const addRes = await relationCollection.add({
        supervisor_id: sid.uid,
		consultant_id: cid.uid,
        createAt:new Date()
      });

      return {
        code: 0,
        message: '关系建立成功',
        data: {
          relation_id: addRes.id
        }
      };

    } else if (action === 'c') {
      // 取消关系逻辑
      // 查找并删除关系
      const deleteRes = await relationCollection.where({
        supervisor_id: sid.uid,
		consultant_id: cid.uid
      }).remove();

      if (deleteRes.deleted === 0) {
        return {
          code: 404,
          message: '关系不存在'
        };
      }

      return {
        code: 0,
        message: '关系已解除',
        data: {
          deleted_count: deleteRes.deleted
        }
      };

    } else {
      return {
        code: 400,
        message: '无效的操作类型'
      };
    }

  } catch (err) {
    console.error('处理关系时出错:', err);
    return {
      code: 500,
      message: '服务器内部错误'
    };
  }
};